define(function(require, exports, module) {
  var $ = require("$");

  require("bootstrap_commonrequire");

  require('select2.css');
  require('select2');
  var store = require('store');

  exports.init = function(param) {

    $(document).ready(function() {

      //加载自定义模板-条件区域
      var isSystemAdmin = (store.get("userInfo").userType == -1);
      var tplattrs = {};
      tplattrs.isSystemAdmin = isSystemAdmin;

      var template = require("./useranalyse.tpl");
      var Widget = require("widget");
      var Component = Widget.extend({
        template : template
      });
      new Component({
        attrs : tplattrs,
        renderTo : queryAreaId
      });

      //获取查询条件
      function getCondition() {

        var isvid = $('#isvName').val();

        var applyid = $('#applyName').val();

        //统计周期
        var statisticstype = $('#statisticstype').val();

        //企业名称
        var carrierid = $('#carrierid').val();

        var queryStr = "";
        if (carrierid != '' && carrierid != null) {
          queryStr += ("corpid=" + carrierid + ";");
        }

        if (isvid != '' && isvid != null) {
          queryStr += ("isvid=" + isvid + ";");
        }

        if (applyid != '' && applyid != null) {
          queryStr += ("applyid=" + applyid + ";");
        }

        if (statisticstype != '' && statisticstype != null) {
          queryStr += ("statisticstype=" + statisticstype + ";");
        }

        var daterange = daterangeCom.getPickerRange();
        if (daterange) {
          var daterange = daterange.split("/");
          var startTime = daterange[0];
          var endTime = daterange[1];
          queryStr += "startTime=" + startTime + ";"
          queryStr += "endTime=" + endTime + ";";
        }

        return queryStr;
      }

      // 绑定企业名称下拉列表
      $("#ddlCarrierid").select2({
        placeholder: "企业名称",
        allowClear: true,
        formatNoMatches: "没有匹配的企业",
        ajax: {
          url: GLOBAL.URL.ADMIN_GETCARRIEROPTIONS,
          dataType: 'json',
          delay: 250,
          data: function (term, pageNo) {
            return {
              q: " c.name like '%"+term+"%' ", // search term
              appid: $("#applyName").val(),
              size: 25,
              start: (pageNo-1)*25
            };
          },
          results: function (data, pageNo) {
            var dataObj = eval(data);
            return {results:dataObj};
          },
          cache: true
        }
      });

      // 绑定isv名称下拉列表
      $.ajax({
        type : "POST",
        dataType : "json",
        url : "/user/queryIsv.do",//GLOBAL.URL.ADMIN_GETCARRIEROPTIONS,// wp.huang
        async : false,
        success : function(data) {
          $("#isvName").select2({
            placeholder : "ISV名称",
            allowClear : true,
            data : data
          });
        },
        error : function(data) {
          bootbox.alertTimeout('初始化ISV名称数据失败！');
        }
      });

      // 绑定应用下拉列表
      $.ajax({
        type : "POST",
        dataType : "json",
        url : "/condition/applyName.do",///GLOBAL.URL.GETAPPLYTYPELIST,  ////wp.huang
        async : false,
        // data: "isvid="+$('#isvName').val(),

        success : function(data) {
          $("#applyName").select2({
            placeholder : "应用名称",
            allowClear : true,
            data : data
          });
        },
        error : function(data) {
          bootbox.alertTimeout('初始化应用名称数据失败！');
        }
      });

      //统计方式
      var typeList = [ {
        "id" : 1,
        "text" : "通话总时长"
      }, {
        "id" : 2,
        "text" : "通话总次数"
      } ];
      $('#statisticstype').select2({
        placeholder : "统计类别",
        allowClear : true,
        data : typeList
      });

      $("#carrierid").select2({
        placeholder : "企业名称",
        allowClear : true,
        ajax : {
          url : GLOBAL.URL.ADMIN_GETCARRIEROPTIONS,
          dataType : 'json',
          delay : 250,
          data : function(term, pageNo) {
            return {
              q : " c.name like '%" + term + "%' ", // search term
              size : 25,
              start : (pageNo - 1) * 25
            };
          },
          results : function(data, pageNo) {
            var dataObj = eval(data);
            /*if(dataObj.length>0){   //如果没有查询到数据，将会返回空串
              var more = (pageNo*15)<dataObj.length; //用来判断是否还有更多数据可以加载
              return {
                results:dataObj,more:more    
              };
            }else{
                return {results:dataObj};
            }*/
            return {
              results : dataObj
            };
          },
          cache : true
        }
      });

      // 初始化日期范围选择控件
      var DateRange = require('daterangeinput');
      var daterangeAttrs = {
        daterangeId : "querydatewrapper_rang",
        label : "日期"
      };
      var daterangeCom = new DateRange({
        attrs : daterangeAttrs,
        renderTo : 'querydatewrapper'
      });

      daterangeCom.setRangeToToday();

      //加载表单模板和数据
      var Table = require("table");
      new Table({
        attrs : {
          id : "datatableid",
          isHovered : false,
          isStriped : true,
          isBordered : false
        },
        renderTo : param.divWrapperId

      });

      var dtUtil = require('datatableutil');

      var datatable = $('#datatableid').dataTable({
        "sDom" : "<'hidden'<'span6'l><'hidden'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
        "bJQueryUI" : false,
        "oLanguage" : {
          "sUrl" : "/business/js/common/table/src/lang/dataTable.cn.txt"
        },
        "sPaginationType" : "bootstrap", // 分页自带两种样式，full_numbers和two_button(默认)
        'bPaginate' : true, // 是否分页
        "bProcessing" : true, // 当datatable获取数据时候是否显示正在处理提示信息。
        "bServerSide" : true, // 指定服务器端分页
        "bDeferRender" : true,
        "bFilter" : true,
        "bSort" : true,
        "bInfo" : true,
        "sAjaxSource" : "/data/userAnalyse.do", // 数据源
        "iDisplayLength" : DATATABLES_CONFIG.iDisplayLength.DEFAULT, // 默认分页的每页记录数
        "fnServerData" : function(sSource, aoData, fnCallback, oSettings) {

          var queryparam = dtUtil.convert_aoData(aoData);

          //拼接where查询条件
          var cond = getCondition();
          if (cond != '' && cond != null) {
            queryparam.q += cond;
          }

          // 添加自己的额外参数
          oSettings.jqXHR = $.ajax({
            "dataType" : 'json',
            "contentType" : "application/json;charset=UTF-8",
            "type" : "GET",
            "url" : sSource,
            "data" : queryparam, // 将请求数据转换为后台要求的JSON格式
            "success" : function(json) {
              dtUtil.successCallback(json, aoData, fnCallback);
            }
          });

        },

        "aoColumns" : [ {
          "sTitle" : "手机号",
          "bSortable" : false,
          "mData" : "phone",
          "sWidth" : "40%"
        }, {
          "sTitle" : "通话总时长(分)",
          "bSortable" : false,
          "mData" : "callingduration",
          "sWidth" : "30%"
        },

        {
          "sTitle" : "通话总次数(次)",
          "bSortable" : false,
          "mData" : "number",
          "sWidth" : "30%"
        }

        ],
        "fnDrawCallback" : function(oSettings) {
          // 表格绘制完成后，去除width属性，使表格可缩放
          $('#' + oSettings.sTableId).css("width", "");
        }
      });

      $('#btnquery').click(function() {
        datatable.fnDraw();
        return false;
      });

      //重置查询条件
      $('#btnreset').click(function() {
        $("#ddlCarrierid").select2("val", "");
        $("#isvName").select2("val", "");
        $("#applyName").select2("val", "");

        return false;
      });

    });

  };
});
